using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Decav.Gatsb.Configuration;

namespace Decav.Gatsb.Web.Controls
{
    /// <summary>
    /// A drop down list that shows all the wireless providers.
    /// </summary>
    public class WirelessProviderDropDown : DropDownList
    {
        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                foreach (MobileProviderConfiguration item in GatsbConfigurationSection.Current.MobileProviders)
                {
                    this.
                        Items.Add(new ListItem(
                        item.Name, item.Type));
                }

                if (!string.IsNullOrEmpty(_providerTypeName))
                    SelectedType = _providerTypeName;
            }

            base.OnLoad(e);
        }

        /// <summary>
        /// Gets or sets the type string of the selected item in the dropdown.
        /// </summary>
        public string SelectedType
        {
            get
            {
                return SelectedValue;
            }
            set
            {
                _providerTypeName = value;

                if (Items.Count == 0)
                    return;

                if (value == string.Empty)
                {
                    SelectedIndex = 0;
                    return;
                }

                for (int i = 0; i<Items.Count;i++)
                {
                    if (Items[i].Value == value)
                    {
                        SelectedIndex = i;
                        return;
                    }
                }

                throw new ArgumentException("The specified provider is not a valid provider type.");
            }
        }

        private string _providerTypeName;

        public void SetSelectedType(TelephoneServiceProvider provider)
        {
            if (provider == null)
                throw new ArgumentNullException("provider");
        
            SelectedType = provider.GetTypeString();
        }
    }
}
